package com.clouddot.baipai.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.getClassInfo.getClassInfoResponse;
import com.clouddot.baipai.model.beam.getClassType.getClassTypeResponse;
import com.clouddot.baipai.model.beam.login.loginResponse;
import com.clouddot.baipai.ui.adapter.H_Adapter.OnDoubleClickListener;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.cameraView.CameraActivity;
import com.clouddot.baipai.ui.dialog.A_updateDailog;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_SettingDailog;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_AttendanceFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_ClassFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_HomeFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_HomeworkFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_MineFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_NewsFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_ScanFaceFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_SchoolFragment;
import com.clouddot.baipai.ui.fragment.H_MainFragment.H_TableableFragment;
import com.clouddot.baipai.ui.util.Ftp.DownFileUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.getTimeAndWeatherUtil;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import org.dom4j.DocumentException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android_serialport_api.sample.SerialPortActivity;


public class H_SMainActivity extends SerialPortActivity implements View.OnClickListener {
    static {
        System.loadLibrary("serial_port");
    }

    /**
     * 1 - 代表每秒刷新时间的返回值
     * 2 - 天气预报
     * 3 - 禁止底部导航栏的出现
     * 4 - 刷卡
     * 5 - 登录时间
     */

    public static final int MSG_ONE = 1;
    public static final int MSG_TWO = 2;
    public static final int MSG_THREE = 3;
    public static final int MSG_FOUR = 4;
    public static final int MSG_FIVE = 5;
    public static final int MSG_SIX = 6;
    public static  int backTime = -1; //返回主界面时间 ，10秒

    private TextView Tvtime,Tvdate,Tvweather,classInfo,className,loginTime; //class信息
    private LinearLayout linearLayout1,linearLayout2,linearLayout3,linearLayout4,linearLayout5, //下方的按钮
            linearLayout6,linearLayout7,linearLayout8,linearLayout9,linearLayout10;
    private LinearLayout[] linearLayouts = new LinearLayout[9];
    private ImageView img1,img2,img3,img4,img5,img6,img7,img8,img9,img10;
    private ImageView [] imageViews = new ImageView[9];
    private Fragment[] fragments = new Fragment[9];
    private ConstraintLayout top; // 双击顶部进入设置界面
    private LinearLayout[] linearLayout = new LinearLayout[2]; // 进入设置界面弹出的dialog的按钮
    private EditText pass; //输入密码框
    private int currentShowFragmentIndex = 0;  //记录当前fragment的序号
    private boolean isScanCard = false; //判断当前刷卡机制是否在运行
    private int time = -1; //登录的剩余时间 ，登录时90秒
    private LoginThread loginThread ;// 每秒刷新登录剩下时间
    private ModleThread modleThread; // 更新设备模式;
    private BackMainThread backMainThread; //返回主界面 ;
    private Thread TimeThread; //更新时间
    private boolean isActivity = false; //当前有没有离开activity
    private View view;
    private boolean isLockSet = false;
    private boolean isLock = true;
    private String cityName;
    private List<Map<String ,String>> mapList; //存放天气预报信息
    private Animation animation; // 点击底部按钮的动画
    private String cardCode = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Environment.getInstance().activities.add(this); //把activity记录起来，方便后面直接调用


        if(TimeThread == null) {
            TimeThread = new Thread(getTimeBySecond);
            TimeThread.start();
        }

        if (Env.getAppContext().isInitial) {
            modleThread = new ModleThread();
            loginThread = new LoginThread();
            backMainThread = new BackMainThread();
            modleThread.start();
            loginThread.start();
            backMainThread.start();
        } else {
            ToastUtil.showToast(this, "还没有设置端口号，请双击顶部栏去到设置界面");
        }

    }

    @Override
    protected void setContentView() {
        super.setContentView();
        setContentView(R.layout.h_a_main);
    }

    @Override
    protected void initControls() {
        super.initControls();

        top = find(R.id.top);

        Tvtime = find(R.id.time);
        Tvdate = find(R.id.date);
        Tvweather = find(R.id.weather);
        className = find(R.id.className);
//        classInfo = find(R.id.classInfo);

        linearLayout1 = find(R.id.home);
        linearLayout2 = find(R.id.home1);
        linearLayout3 = find(R.id.home2);
        linearLayout4 = find(R.id.home3);
//        linearLayout5 = find(R.id.home4);
        linearLayout6 = find(R.id.home5);
        linearLayout7 = find(R.id.home6);
        linearLayout8 = find(R.id.home7);
        linearLayout9 = find(R.id.home8);
        linearLayout10 = find(R.id.home9);

        linearLayouts[0] = linearLayout1;
        linearLayouts[1] = linearLayout2;
        linearLayouts[2] = linearLayout3;
        linearLayouts[3] = linearLayout4;
//        linearLayouts[4] = linearLayout5;
        linearLayouts[4] = linearLayout6;
        linearLayouts[5] = linearLayout7;
        linearLayouts[6] = linearLayout8;
        linearLayouts[7] = linearLayout9;
        linearLayouts[8] = linearLayout10;



        img1 = find(R.id.img1);
        img2 = find(R.id.img2);
        img3 = find(R.id.img3);
        img4 = find(R.id.img4);
//        img5 = find(R.id.img5);
        img6 = find(R.id.img6);
        img7 = find(R.id.img7);
        img8 = find(R.id.img8);
        img9 = find(R.id.img9);
        img10 = find(R.id.img10);

        imageViews[0] = img1;
        imageViews[1] = img2;
        imageViews[2] = img3;
        imageViews[3] = img4;
//        imageViews[3] = img5;
        imageViews[4] = img6;
        imageViews[5] = img7;
        imageViews[6] = img8;
        imageViews[7] = img9;
        imageViews[8] = img10;

        fragments[0] = new H_HomeFragment();
        fragments[1] = new H_SchoolFragment();
        fragments[2] = new H_ClassFragment();
        fragments[3] = new H_NewsFragment();
//        fragments[4] = new H_ActionFragment();
        fragments[4] = new H_TableableFragment();
        fragments[5] = new H_AttendanceFragment();
        fragments[6] = new H_HomeworkFragment();
        fragments[7] = new H_MineFragment();
        fragments[8] = new H_ScanFaceFragment();

        if( Env.getAppContext().openScan ){
            linearLayout10.setVisibility(View.VISIBLE);
        }else {
            linearLayout10.setVisibility(View.GONE);

        }
        animation = AnimationUtils.loadAnimation(H_SMainActivity.this,R.anim.buttom_click_anim);

        animation.setDuration(200);
//        startAnim();
        view = getWindow().getDecorView();

        loginTime = find(R.id.lodinTime);

    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }


    @Override
    protected void setListener() {
        super.setListener();

        for(LinearLayout linearLayout :linearLayouts) linearLayout.setOnClickListener(this);
        top.setOnTouchListener(onDoubleClickListener);
        view.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            if(!isLockSet){
                                handler.sendEmptyMessage(MSG_THREE);
                            }
                        } else {
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActivity = false;
        isScanCard = false;
        handler.sendEmptyMessage(MSG_THREE);
        if(Env.getAppContext().isInitial) {
            runThreadAction();      //获取天气预报
            runThreadAction("getClassInfo"); //获取班级信息
//            runThreadAction("2446555318");
//            runThreadAction("3754873335");

            if (Env.getAppContext().isUpdata && Env.getAppContext().isCancleUpdate && !Env.getAppContext().isAutoUpdate) { //判断是否要升级
                Env.getAppContext().isCancleUpdate = false;
                DownFileUtil.downloadFile(H_SMainActivity.this);
            }
            className.setText("正在查询绑定班级...");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivity = true;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(loginThread != null) loginThread.stopRun();
        if(modleThread != null)  modleThread.stopRun();
        if(backMainThread != null)  backMainThread.stopRun();
    }

    @Override
    public void runThreadAction() {
        super.runThreadAction();
    }

    @Override
    protected Object runThreadActionExceute() {
         super.runThreadActionExceute();

         return Env.getAppPresenter().getWeatherInfo("101270101");
//         101270101"101280101"
    }

    @Override
    protected void runThreadActionSuccess(final Object result){
        super.runThreadActionSuccess(result);

        new Thread(new Runnable() {
            @Override
            public void run() {
            try {
                mapList = getTimeAndWeatherUtil.getWeatherInfo((String) result);
                Message msg = new Message();
                msg.what = MSG_TWO;
                handler.sendMessage(msg);
            } catch (DocumentException e) {
                e.printStackTrace();
            }

            }
        }).start();
    }

    @Override
    protected void runThreadActionError(Exception ex) {
        super.runThreadActionError(ex);
    }


    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);

    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
         super.runThreadActionExceute(actionName);
         if(actionName.equals("getClassInfo")){
             return  Env.getAppPresenter().getClassInfo(Env.getAppContext().carddevid);
         }else{
             try {
                 if(Env.getAppContext().isAutoTakePhoto){
                     return  Env.getAppPresenter().login(actionName, URLEncoder.encode(filePath, "UTF-8"));

                 }else{
                     return Env.getAppPresenter().login(actionName);
                 }
             } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
             }
         }

        return null;
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.equals("getClassInfo")){
            getClassInfoResponse response = (getClassInfoResponse) result;
            if(response.isSuccess()){
                className.setText(response.ClassName);
            }else{
                ToastUtil.showToast(this,response.getErrMsg());
                if(response.getErrMsg().equals("班级获取失败，请点击重试")) {
                    className.setOnClickListener(getclassInfoListener);
                }
                className.setText(response.getErrMsg());
            }
            selectLinear(0);

        }else{
            loginResponse response = (loginResponse) result;
            if(response.isSuccess()){
                SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[5]);
                imageViews[5].startAnimation(animation);
                showFragment(5,5);
                time = 90;
                loginTime.setText(time+"");
                loginTime.setVisibility(View.VISIBLE);
                Env.getAppContext().cardID = actionName;
            }else{
                ToastUtil.showToast(this,response.getErrMsg());
            }
            isScanCard = false;
            cardCode = "";
            filePath = "";
            isNew = true;
        }
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    @Override
    public void onClick(View view) {
        backTime = Env.getAppContext().backMainTime * 60;

        switch (view.getId()){
            case R.id.home:
                backTime = -1;
                selectLinear(0);
                break;
            case R.id.home1:
                selectLinear(1);
                break;
            case R.id.home2:
                selectLinear(2);
                break;
            case R.id.home3:
                selectLinear(3);
                break;
//            case R.id.home4:
//                selectLinear(4);
//                break;
            case R.id.home5:
                selectLinear(4);
                break;
            case R.id.home6:
                selectLinear(5);
                break;
            case R.id.home7:
                selectLinear(6);
                break;
            case R.id.home8:
                selectLinear(7);
                break;
            case R.id.home9:
                selectLinear(8);
                break;
        }
    }


    String filePath = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                initControls();
                setListener();
                showFragment(0,0);
                break;
            case 123:
                Bundle bundle = data.getExtras();
                String fileinfo = bundle.getString("back");

                try {
                    JSONObject myJsonObject = new JSONObject(fileinfo);
                    filePath = myJsonObject.getString("FilePath");
                    Log.i( "onActivityResult: ",filePath);
                    ToastUtil.showToast(H_SMainActivity.this, "扫描学号：" + cardCode, Toast.LENGTH_SHORT);
                    runThreadAction(cardCode);
                }
                catch(Exception ex) {

                }

                break;
            default:
                break;
        }

    }


    /**
     * 刷卡接收数据
     */
    private boolean isNew = true;
    private List<byte[]> bytes = new ArrayList<>();

    @Override
    protected void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (!TextUtils.isEmpty(Env.getAppContext().host)) {

//                    if (cardCode != null) {
//                        if (isNew) {
//                            isNew = false;
//                            cardCode = "";
//                        }
//                        cardCode += new String(buffer, 0, size);
//
//                        handler.removeMessages(H_SMainActivity.MSG_FOUR);
//                        handler.sendEmptyMessageDelayed(H_SMainActivity.MSG_FOUR, 1000);
//                }
                    if (cardCode != null) {
                        if (isNew) {
                            isNew = false;
                            cardCode = "";
                            bytes.clear();
                        }
                        bytes.add(buffer);
                        handler.removeMessages(MSG_FOUR);
                        handler.sendEmptyMessageDelayed(MSG_FOUR, 1000);
                    }
                } else {
                    ToastUtil.showToast(H_SMainActivity.this, "还没有设置端口号，请双击顶部栏去到设置界面");
                }
            }

        });

    }


    /**
     *
     * 结束获取信息的handle机制
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    Thread timeThread = new Thread(getTimeBySecondToView);
                    timeThread.start();
                    break;
                case MSG_TWO:
                    if(mapList.size() > 1){
                        Tvweather.setText(mapList.get(41).get("type")+"\t" +mapList.get(2).get("wendu")+" ℃");
                    }else{
                        Tvweather.setText("获取天气信息失败");
                    }
                    break;
                case MSG_THREE:
                    isLockSet = true;
                    if (isLock) {
                        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    } else {
                        int uiFlags = View.SYSTEM_UI_FLAG_VISIBLE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    }
                    isLockSet = false;
                    break;

                case MSG_FOUR:
                    if(!isScanCard){
                        if( !isActivity) {
                            isScanCard = true;
//                            String code = cardCode.replaceAll("\r", "").replaceAll("\n", "").trim();
//                            cardCode = EscapeUnescapeUtil.StringTo10(code);
                            String codes = "";
                            for(int j =  0 ; j <bytes.size();j++){
                                for(int i = 0; i < bytes.get(j).length ; i++){
                                    String code = String.format("%02X", bytes.get(j)[i]);
                                    if(!code.equals("00")) {
                                        codes += code;
                                    }else{
                                        break;
                                    }
                                }
                            }
                            if(codes.length() > 16) {
                                if (codes.substring(4, 6).equals("01")) {
                                    cardCode = codes.substring(6, 14);
                                } else if (codes.substring(4, 6).equals("02")) {
                                    cardCode = codes.substring(6, 16);
                                } else {
                                    ToastUtil.showToast(H_SMainActivity.this, "读卡器识别不了这张卡！");
                                    return;
                                }
                                cardCode = EscapeUnescapeUtil.StringTo10(cardCode);
                                if (Env.getAppContext().isAutoTakePhoto) {
                                    Toast.makeText(H_SMainActivity.this, "拍照中，请对准摄相头", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent();
                                    intent.setClass(H_SMainActivity.this, CameraActivity.class);
                                    startActivityForResult(intent, 123);
                                } else {
                                    ToastUtil.showToast(H_SMainActivity.this, "扫描学号：" + cardCode, Toast.LENGTH_SHORT);
                                    runThreadAction(cardCode);
                                }
                            }else{
                                isNew = true;
                                isScanCard = false;
                            }

                        }
                    }else{
                        ToastUtil.showToast(H_SMainActivity.this,"正在通信中,不用再次刷卡");
                    }
                    break;
                case MSG_FIVE:
                    //剩余时间的显示
                    if(Env.getAppContext().StudentId != null) {
                        if (time == 0) {
                            loginTime.setVisibility(View.GONE);
                            Env.getAppContext().StudentId = null;
                            if (!isActivity) selectLinear(0);
                            time = -1;
                        } else {
                            time--;
                            if (!isActivity) loginTime.setText(time + "");
                        }
                    }else{
                        loginTime.setVisibility(View.GONE);
                        time = -1;
                    }

                    break;
                case MSG_SIX:
                    //剩余时间的显示
                        if (backTime == 0) {
                            if (!isActivity) selectLinear(0);
                            backTime = -1;
                        } else {
                            backTime--;
                        }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     *
     * 点击按钮开始动画
     */
    public void selectLinear(int i){
        if(!Env.getAppContext().host.equals("")) {
            if(Env.getAppContext().scanFaceUrl.equals("") && i == 8){
                ToastUtil.showToast(this,"还没有设置刷脸的url，请双击顶部栏去到设置界面");
                return;
            }

            SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[i]);
            imageViews[i].startAnimation(animation);
            showFragment(i, 10);

        }else{
            ToastUtil.showToast(this,"还没有设置端口号，请双击顶部栏去到设置界面");
        }
    }

    /**
     *
     * 启动时按钮动画
     */
    private void startAnim(){
        int duration = 500;

        for (int i = 0 ;i < linearLayouts.length; i++){
            Animation animation1 = AnimationUtils.loadAnimation(H_SMainActivity.this,R.anim.buttom_start_anim);
            animation1.setDuration(duration);
            linearLayouts[i].startAnimation(animation1);
            duration += 200;
        }
    }

    /**
     *
     * 点击按钮切换fragment
     */
    private void showFragment(int index,int currentIndex){
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            // 动作1:隐藏当前
            transaction.hide(fragments[currentShowFragmentIndex]);
            Fragment showFragment = null;
            // 动作2:添加要显示的
            if(currentIndex == 5){
                showFragment = new H_AttendanceFragment();
            }else if(currentIndex == 0){
                showFragment = new H_HomeFragment();
            } else{
                showFragment = fragments[index];
            }
            if (!showFragment.isAdded())
            {
                transaction.replace(R.id.fragmentP, showFragment);
            }
            // 动作3:显示出来
            transaction.show(showFragment);
            // 提交事务
            transaction.commit();
            currentShowFragmentIndex = index;

    }

    /**
     * 双击操作
     *
     */
//
    private OnDoubleClickListener onDoubleClickListener = new OnDoubleClickListener(
            new OnDoubleClickListener.DoubleClickCallback()
            {
                @Override
                public void onDoubleClick()
                {

                    final H_SettingDailog dailog = new H_SettingDailog(H_SMainActivity.this);
                    linearLayout = dailog.getBtnView();
                    linearLayout[0].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            pass = dailog.getPass();

                            if(!TextUtils.isEmpty(pass.getText().toString()) && pass.getText().toString().equals(Env.getAppContext().password)){
                                dailog.closeDialog();
                                startActivityForResult(new Intent(H_SMainActivity.this,H_SettingActivity.class),1);
                            }else {
                                ToastUtil.showToast(H_SMainActivity.this,"密码错误");
                                pass.setText("");
                            }

                        }
                    });
                    linearLayout[1].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            dailog.closeDialog();
                        }
                    });
                    dailog.showDialog();

                }

            });



    /**
     *
     * 每秒获取系统时间
     */
    private Runnable getTimeBySecond = new Runnable() {
        @Override
        public void run() {
            do {
                try {

                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = MSG_ONE;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    };

    /**
     *
     * 登录剩余时间监听
     */
    private class BackMainThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                     msg.what = MSG_SIX;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (!stopFlag);
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    }
    /**
     * 登录剩余时间监听
     */
    private class LoginThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = MSG_FIVE;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (!stopFlag);
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    };
    private boolean flag = true;
    private class ModleThread extends Thread {
        private boolean stopFlag = false;

        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isActivity) {
                    getClassTypeResponse response = Env.getAppPresenter().getClassType();
                    if (response.isSuccess()) {

                        if (!response.Value.equals("Common")) {
                            flag = false;
                            Env.getAppContext().type = response.Value;
                            Env.getAppContext().DevicePath = response.DevicePath;
                            Intent i = new Intent(H_SMainActivity.this, A_LaunchActivity.class);
                            H_SMainActivity.this.startActivity(i);
                        }
                    }
                }
            } while (flag && !isActivity  && !stopFlag);
        }
        private void stopRun() {
            stopFlag = true;
        }
    };
    /**
     *
     * 获取系统时间并且渲染在视图
     */
    private Runnable getTimeBySecondToView = new Runnable() {
        @Override
        public void run() {
            final String data = getTimeAndWeatherUtil.getTimeAndData();
            final String []value = data.split("-");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Tvtime.setText(value[1]);
                    Tvdate.setText(value[0] + "\t" + value[2]);
                }
            });
        }
    };
    /**
     *
     * 升级安装包
     */
    private LinearLayout[] btns = new LinearLayout[2];
    private TextView textView;
    private void startUpdate() {
        final A_updateDailog dailog = new A_updateDailog(H_SMainActivity.this);
        btns = dailog.getBtnView();
        textView = dailog.getTextView();
        dailog.showDialog();

        textView.setText(Env.getAppContext().updateTip);

        btns[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Env.getAppContext().isCancleUpdate = false;
                dailog.closeDialog();
            }
        });

        btns[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Env.getAppContext().isCancleUpdate = false;
                DownFileUtil.downloadFile(H_SMainActivity.this);

                dailog.closeDialog();
            }
        });
    }

    private View.OnClickListener getclassInfoListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                className.setText("正在查询绑定班级...");
                runThreadAction("getClassInfo"); //获取班级信息

        }
    };
}

